package com.codrim.cs.data.server.rpc;

import com.alibaba.dubbo.config.annotation.Service;
import com.codrim.common.utils.exception.Assert;
import com.codrim.cs.data.rpc.ReportRecordService;
import com.codrim.cs.data.rpc.dto.ReportRecordDTO;
import com.codrim.cs.data.server.dao.entity.ReportRecordDO;
import com.codrim.cs.data.server.dao.mapper.ReportRecordMapper;
import com.codrim.cs.data.server.subservice.TimeZoneSubService;

import org.apache.commons.lang3.math.NumberUtils;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;

import javax.annotation.Resource;

/**
 * @author Liang.Zhuge on 10/07/2017.
 */
@Service(version = ReportRecordService.RPC_VERSION)
public class ReportRecordServiceImpl implements ReportRecordService {
    private static final String YYYY_MM_DD = "yyyyMMdd";
    private static final String YYYY_MM_DD_HH_MM_SS = "yyyyMMddHHmmss";
    @Resource ReportRecordMapper reportRecordMapper;
    @Resource TimeZoneSubService timeZoneSubService;

    @Override
    public ReportRecordDTO lastOne() {
        final ReportRecordDO lastOne = reportRecordMapper.findLastOne();
        return lastOne == null ? null : lastOne.toReportRecordDTO();
    }

    @Override
    public void insert(ReportRecordDTO reportRecordDTO) {
        Assert.notNull(reportRecordDTO, "Param can not be null");
        reportRecordMapper.insert(new ReportRecordDO(reportRecordDTO));
    }

    @Override
    public void deleteSpecifiedDayReportRecord(String dateTime, int zoneNumber) {
        Assert.notBlank(dateTime, "dateTime can not be null");
        Assert.isTrue(dateTime.length() == 8 && NumberUtils.isCreatable(dateTime), "invalid dateTime eg: 20170805");
        DateTime startPoint = DateTimeFormat.forPattern(YYYY_MM_DD).withZone(DateTimeZone.UTC).parseDateTime(dateTime)
                .plusHours(zoneNumber);
        DateTime endPoint = DateTimeFormat.forPattern(YYYY_MM_DD).withZone(DateTimeZone.UTC).parseDateTime(dateTime)
                .plusHours(zoneNumber + 24);
        long beginTime = NumberUtils.toLong(startPoint.toString(YYYY_MM_DD_HH_MM_SS));
        long endTime = NumberUtils.toLong(endPoint.toString(YYYY_MM_DD_HH_MM_SS));
        reportRecordMapper.deleteByBeginTimeEndTimeAndZone(beginTime, endTime,
                timeZoneSubService.prefixTableNameForTimeZone(zoneNumber));
    }
}
